package cart;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/orderServlet")
public class OrderServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Gson gson = new GsonBuilder().create();

        // 从 session 中获取用户 id（下单时必须登录，且 session 中存放了 userId）
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("userId") == null) {
            out.write("{\"status\":\"error\",\"message\":\"请先登录\"}");
            return;
        }
        int userId = (Integer) session.getAttribute("userId");

        // 获取前端传入的产品名称和价格
        String productName = request.getParameter("productName");
        String priceStr = request.getParameter("price");
        if (productName == null || priceStr == null) {
            out.write("{\"status\":\"error\",\"message\":\"缺少参数\"}");
            return;
        }
        double price;
        try {
            price = Double.parseDouble(priceStr);
        } catch (NumberFormatException e) {
            out.write("{\"status\":\"error\",\"message\":\"价格格式错误\"}");
            return;
        }

        Connection conn = null;
        PreparedStatement ps = null;
        String sql = "INSERT INTO orders (user_id, product_name, total) VALUES (?, ?, ?)";
        try {
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, userId);
            ps.setString(2, productName);
            ps.setDouble(3, price);
            int rows = ps.executeUpdate();
            if (rows > 0) {
                out.write("{\"status\":\"success\"}");
            } else {
                out.write("{\"status\":\"error\",\"message\":\"下单失败\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.write("{\"status\":\"error\",\"message\":\"" + e.getMessage() + "\"}");
        } finally {
            try { if (ps != null) ps.close(); } catch (SQLException ex) {}
            try { if (conn != null) conn.close(); } catch (SQLException ex) {}
        }
    }
}
